package com.jxwifi.cloud.quickcleanserver.utils;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.ImageFormat;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;

import com.idroid.utils.PxUtils;
import com.jxwifi.cloud.quickcleanserver.R;

/**
 * 计时动画效果View实现类
 * Created by Administrator on 2019/5/17.
 */

public class CountDownView extends View {
    //圆轮颜色
    private int mRingColor;
    //圆轮宽度
    private float mRingWidth;
    //圆轮进度值文本大小
    private int mRingProgessTextSize;
    //宽度
    private int mWidth;
    //高度
    private int mHeight;
    private Paint mPaint;
    //圆环的矩形区域
    private RectF mRectF;
    private int mProgessTextColor;
    private int mCountdownTime;
    private float mCurrentProgress;
    private OnCountDownFinishListener mListener;

    public ValueAnimator valueAnimator;

    //新增字段表示显示的时间
    private String mWorkTime = "00:00:00";

    public CountDownView(Context context) {
        this(context, null);
    }

    public CountDownView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CountDownView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CountDownView);
        mRingColor = a.getColor(R.styleable.CountDownView_ringColor, context.getResources().getColor(R.color.color_white));
        mRingWidth = a.getFloat(R.styleable.CountDownView_ringWidth, 10);
        mRingProgessTextSize = a.getDimensionPixelSize(R.styleable.CountDownView_progressTextSize, PxUtils.sp2px(context, 50));
        mProgessTextColor = a.getColor(R.styleable.CountDownView_progressTextColor, context.getResources().getColor(R.color.color_white));
        mCountdownTime = a.getInteger(R.styleable.CountDownView_countdownTime, 60);
        //注意：记得回收
        a.recycle();
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setAntiAlias(true);
        this.setWillNotDraw(false);
    }

    public void setCountdownTime(int mCountdownTime) {
        this.mCountdownTime = mCountdownTime;
    }

    public void setWorkTime(String mWorkTime) {
        this.mWorkTime = mWorkTime;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        mWidth = getMeasuredWidth();
        mHeight = getMeasuredHeight();
        mRectF = new RectF(0 + mRingWidth / 2, 0 + mRingWidth / 2, mWidth - mRingWidth / 2, mHeight - mRingWidth / 2);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //颜色
        mPaint.setColor(mRingColor);
        //空心
        mPaint.setStyle(Paint.Style.STROKE);
        //宽度
        mPaint.setStrokeWidth(mRingWidth);
        canvas.drawArc(mRectF, -90, mCurrentProgress - 360, false, mPaint);
        //绘制文本
        Paint textPaint = new Paint();
        textPaint.setAntiAlias(true);
        textPaint.setTextAlign(Paint.Align.CENTER);
        //String text = mCountdownTime - (int) (mCurrentProgress / 360f * mCountdownTime) + "";
        String text = mWorkTime.substring(0,mWorkTime.length()-3);
        textPaint.setTextSize(mRingProgessTextSize);
        textPaint.setColor(mProgessTextColor);
        //文字居中显示
        Paint.FontMetricsInt fontMetrics = textPaint.getFontMetricsInt();
        int baseline = (int) ((mRectF.bottom + mRectF.top - fontMetrics.bottom - fontMetrics.top) / 2);
        canvas.drawText(text, mRectF.centerX(), baseline, textPaint);
    }

    private ValueAnimator getValA(long countdownTime) {
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 100);
        valueAnimator.setDuration(countdownTime);
        valueAnimator.setInterpolator(new LinearInterpolator());
        return valueAnimator;
    }
    /**
     * 开始倒计时
     */
    public void startCountDown() {
        valueAnimator = getValA(60 * 1000);
        Log.w("oushuhua","倒计时的总时间");
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float i = Float.valueOf(String.valueOf(animation.getAnimatedValue()));
                mCurrentProgress = (int) (360 * (i / 100f));
                invalidate();
            }
        });
        valueAnimator.start();
        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mListener.countDownFinished();
                addSecond(60);
                valueAnimator.start();

            }
        });
    }

    public void setAddCountDownListener(OnCountDownFinishListener mListener) {
        this.mListener = mListener;
    }

    public interface OnCountDownFinishListener {
        void countDownFinished();
    }

    private boolean isAnimatorPause = false;

    //暂停动画
    public void animatorCancel() {
        if (valueAnimator != null){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                valueAnimator.pause();
            }else{
                if (!isAnimatorPause){
                    valueAnimator.cancel();
                }
                isAnimatorPause = true;
            }
        }
    }

    //开始动画
    public void startanimator(){
        if (valueAnimator != null){
            valueAnimator.start();
        }
    }

    //释放动画
    public void atcancel(){
        if (valueAnimator != null){
            valueAnimator.cancel();
        }
    }

    //时间数据(给外部调用)
    public String mgetTime(){
        return mWorkTime;
    }

    public void addSecond(long addTime) {
        long mNewSecond = formatTurnSecond(mWorkTime) + addTime;//先转化为秒
        String mHour = change((int) mNewSecond);
        mWorkTime = mHour;
        invalidate();//刷新自定义的View
    }

    /*
 * 将时分秒转为秒数
 * */
    public long formatTurnSecond(String time) {
        if (!time.equals("00:00:00")){
            String s = time;
            int index1 = s.indexOf(":");
            int index2 = s.indexOf(":", index1 + 1);
            int hh = Integer.parseInt(s.substring(0, index1));
            int mi = Integer.parseInt(s.substring(index1 + 1, index2));
            int ss = Integer.parseInt(s.substring(index2 + 1));

            Log.e("oushuhua", "formatTurnSecond: 时间== " + hh * 60 * 60 + mi * 60 + ss);
            return hh * 60 * 60 + mi * 60 + ss;
        }else{
            return 0;
        }
    }

    /*
    * 将秒数转为时分秒
    * */
    public String change(int second) {
        int h = 0;
        int d = 0;
        int s = 0;
        int temp = second % 3600;
        if (second >= 3600) {
            h = second / 3600;
            if (temp != 0) {
                if (temp >= 60) {
                    d = temp / 60;
                    if (temp % 60 != 0) {
                        s = temp % 60;
                    }
                } else {
                    s = temp;
                }
            }
        } else {
            d = second / 60;
            if (second % 60 != 0) {
                s = second % 60;
            }
        }
        return String.format("%2d", h).replace(" ", "0") + ":" + String.format("%2d", d).replace(" ", "0")+ ":" + String.format("%2d", s).replace(" ", "0") + "";
    }

}
